package com.izouma;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

public class SignatureGenerator {

    // 加载私钥
    private static PrivateKey loadPrivateKey(String privateKeyPath) throws Exception {
        String pemContent = new String(Files.readAllBytes(Paths.get(privateKeyPath)), StandardCharsets.UTF_8);
        String privateKeyPEM = pemContent.replace("-----BEGIN PRIVATE KEY-----", "")
                .replace("-----END PRIVATE KEY-----", "")
                .replaceAll("\\s+", "");

        byte[] encodedPrivateKey = Base64.getDecoder().decode(privateKeyPEM);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }

    // 生成签名
    public static String generateSignature(String httpMethod, String urlPath, long timestamp, String nonce, String requestBody, PrivateKey privateKey) throws Exception {
        StringBuilder stringToSign = new StringBuilder();
        stringToSign.append(httpMethod).append("\n")
                .append(urlPath).append("\n")
                .append(timestamp).append("\n")
                .append(nonce).append("\n")
                .append(requestBody != null ? requestBody : "").append("\n");

        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(stringToSign.toString().getBytes(StandardCharsets.UTF_8));

        byte[] signedData = signature.sign();
        return Base64.getEncoder().encodeToString(signedData);
    }

    // 生成随机数
    private static String generateNonce() {
        SecureRandom random = new SecureRandom();
        return String.format("%08x", random.nextInt());
    }

    public static void main(String[] args) {
        try {
            // 私钥文件路径
            String privateKeyPath = "D:\\JuLingGame\\xiangmoji\\src\\main\\resources\\private_key.pem"; // 修改为实际路径
            // 加载私钥
            PrivateKey privateKey = loadPrivateKey(privateKeyPath);

            // 构造参数
            String httpMethod = "POST";
            String urlPath = "/api/business/diamond/query";
            long timestamp = System.currentTimeMillis() / 1000L; // 获取当前时间戳
            String nonce = generateNonce(); // 生成随机串
            String requestBody = "{\"appid\":\"ttxxx\",\"order_id\":\"xxx\"}";

            // 生成签名
            String signature = generateSignature(httpMethod, urlPath, timestamp, nonce, requestBody, privateKey);

            // 输出签名结果
            System.out.println("Generated Signature: " + signature);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}